package com.cyf.app.service.impl;

import com.cyf.activemq.network.bean.*;
import com.cyf.activemq.service.MqService;
import com.cyf.service.bean.CustomException;
import com.cyf.app.network.bean.*;
import com.cyf.app.network.bean.AppCarLockOrNoReq;
import com.cyf.app.network.bean.AppCarLockOrNoRsp;
import com.cyf.app.network.bean.car.*;
import com.cyf.app.service.AppService;
import com.cyf.service.CommonService;
import com.cyf.util.ParkingUtil;
import com.cyf.service.CheckParam;
import com.cyf.app.service.bean.IllegalQuery;
import com.cyf.db.mapper.AppFeedbackMapper;
import com.cyf.db.bean.AppFeedback;
import com.cyf.db.bean.*;
import com.cyf.db.mapper.*;
import com.cyf.util.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.*;

/**
 * app相关接口
 * Created by cage on 2017/2/15.
 */
@Service
public class AppServiceImpl implements AppService {
    private static Logger logger = LoggerFactory.getLogger(AppServiceImpl.class);
    private static final long ONEMINUTE = 60 * 1000;

    @Autowired
    private RegSmsMapper regSmsMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AppCarMapper appCarMapper;
    @Autowired
    private AppUserCarMapper appUserCarMapper;
    @Autowired
    private InParkingMapper inParkingMapper;
    @Autowired
    private ParkingMapper parkingMapper;
    @Autowired
    private InOutParkingMapper inOutParkingMapper;
    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private AppFeedbackMapper appFeedbackMapper;
    @Autowired
    private FeeDetailMapper feeDetailMapper;
    @Autowired
    private MerchantCouponMapper merchantCouponMapper;
    @Autowired
    private AdminparaMapper adminparaMapper;
    @Autowired
    private NpsManageAccountMapper npsManageAccountMapper;
    @Autowired
    private HandsetLoginMapper handsetLoginMapper;
    @Autowired
    private LocalAdminparaMapper localAdminparaMapper;

    @Autowired
    private CheckParam checkParam;
    @Autowired
    private WeChatSubscriptionUtil weChatSubscriptionUtil;
    @Autowired
    private CommonService commonService;

    @Autowired
    private BasicProperties basicProperties;
    @Autowired
    private IllegalQueryUtil illegalQueryUtil;
    @Autowired
    private MqService mqService;

    @Override
    public AppRegSmsRsp sendSms(AppRegSmsReq req) {
        AppRegSmsRsp rsp = new AppRegSmsRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        Integer code = SmsUtils.getCode();
        //String txt = SmsUtils.getTxt(code);
        String txt = SmsUtils.getTxtForApp(code);
        try {
            // 首先查询手机号码是否已经发送过
            RegSms regSms = regSmsMapper.getByMobile(req
                    .getMobile());
            if (regSms != null) {
                long time = new Date().getTime() - regSms.getSmsTime().getTime();
                if (time < ONEMINUTE) {
                    rsp.setStrError("重复提交");
                    return rsp;
                }
                //appRegSmsMapper.deleteById(appRegSms.getId());
                rsp.setResult(AppBusinessRsp.SUCCESS);
                rsp.setStrError("");
                return rsp;
            }
            String rspStr = SmsUtils.SendSms(txt, req.getMobile());
            logger.info("app发送短信验证码结果：{}", rspStr);
            SmsRsp smsRsp = ObjectMapperUtils.getObjectMapper().readValue(rspStr, SmsRsp.class);
            if (SmsRsp.SUCCESS.equals(smsRsp.getCode())) {
                regSms = new RegSms();
                regSms.setMobile(req.getMobile());
                regSms.setSmsTime(new Date());
                regSms.setCode(code);
                regSmsMapper.insertRegSms(regSms);
                rsp.setResult(AppBusinessRsp.SUCCESS);
                rsp.setStrError("");
            } else {
                rsp.setStrError("短信发送失败！");
            }
        } catch (Exception e) {
            logger.error("app发送短信验证码结果异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public AppLoginRsp login(AppLoginReq req) {
        AppLoginRsp rsp = new AppLoginRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        try {
            RegSms regSms = regSmsMapper.getByMobile(req.getMobile());
            if (regSms == null || regSms.getCode() != req.getSmsCode()) {
                rsp.setStrError("验证码错误！");
            } else {
                User user = userMapper.getByMobile(req.getMobile());
                if (user != null) {
                    if (StringUtils.isEmpty(user.getToken())) {
                        user.setToken(UUID.randomUUID().toString().replace("-", ""));
                        switch (user.getUserAuth()) {
                            case User.USERAUTH_SVRAPP:
                                user.setUserAuth(User.USERAUTH_BOTH);
                                break;
                            default:{
                                user.setUserAuth(User.USERAUTH_YTB);
                            }
                        }
                        userMapper.updateAppInfo(user);
                    } else {
                        switch (user.getUserAuth()) {
                            case User.USERAUTH_SVRAPP:
                                user.setUserAuth(User.USERAUTH_BOTH);
                                break;
                            default:{
                                user.setUserAuth(User.USERAUTH_YTB);
                            }
                        }
                        userMapper.updateUserAuthById(user.getUserAuth(), user.getId());
                    }
                    rsp.setToken(user.getToken());
                    Integer carCount = appUserCarMapper.getCountByUserId(user.getId());
                    rsp.setCarCount(carCount == null ? 0 : carCount);
                } else {
                    user = new User();
                    user.setMobile(req.getMobile());
                    user.setCreatedTime(new Date());
                    user.setToken(UUID.randomUUID().toString().replace("-", ""));
                    user.setUserAuth(User.USERAUTH_YTB);
                    userMapper.insertUser(user);
                    rsp.setToken(user.getToken());
                    rsp.setCarCount(0);
                }
                // 用户注册成功，删除发送的短信
                regSmsMapper.deleteByMobile(user.getMobile());
                rsp.setResult(AppBusinessRsp.SUCCESS);
            }
        } catch (Exception e) {
            logger.error("app请求登录异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public AppLogoutRsp logout(AppLogoutReq req) {
        AppLogoutRsp rsp = new AppLogoutRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
//        User user;
//        try {
//            user = checkParam.getAppUser(req.getToken());
//        } catch (CustomException e) {
//            rsp.setResult(AppBusinessRsp.TIMEOUT);
//            rsp.setStrError(e.getMessage());
//            return rsp;
//        }
        try {
            rsp.setResult(AppBusinessRsp.SUCCESS);
        } catch (Exception e) {
            logger.error("app请求登录异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    @Transactional
    public AppAdCarRsp addCar(AppAdCarReq req) {
        AppAdCarRsp rsp = new AppAdCarRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            if (req.getPlate() == null || req.getPlate().trim().length() < 7) {
                rsp.setStrError("车牌号不正确！");
                return rsp;
            }
            String plate = req.getPlate().trim().toUpperCase();
            List<AppCar> appCars = appUserCarMapper.getCarByUserId(user.getId());
            int carCount = null == appCars ? 0 : appCars.size();
            if (carCount == 3) {
                rsp.setStrError("用户车辆已达上限！");
                return rsp;
            }
            if (null != appCars) {
                for (AppCar appCar : appCars) {
                    if (plate.equals(appCar.getPlate())) {
                        rsp.setStrError("请勿注册重复车牌！");
                        return rsp;
                    }
                }
            }
            AppCar appCar = appCarMapper.getByPlate(plate);
            if (appCar == null) {
                appCar = new AppCar(plate);
                appCar.setType(req.getType());
                appCar.setColor(req.getColor());
                appCar.setBrand(req.getBrand());
                appCar.setIsEnergy(req.getIsEnergy());
                appCar.setCheckTime(req.getCheckTime());
                appCar.setRegisterTime(req.getRegisterTime());
                appCar.setMileage(req.getMileage());
                appCar.setUserId(user.getId());
                appCar.setCreateTime(new Date());
                appCarMapper.insertAppCar(appCar);
            }
            appUserCarMapper.insertUserCar(user.getId(), appCar.getId());
            rsp.setResult(AppBusinessRsp.SUCCESS);
            rsp.setCarCount((carCount + 1));
        } catch (Exception e) {
            logger.error("app用户添加车辆异常：{}", e);
            rsp.setStrError("服务器异常");
            // 手动回滚，controller层无需处理异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return rsp;
    }

    @Override
    public AppGetCarsRsp getCars(AppGetCarsReq req) {
        AppGetCarsRsp rsp = new AppGetCarsRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            ArrayList<AppGetCarsItem> plates = new ArrayList<>();
            List<AppCar> appCars = appUserCarMapper.getCarByUserId(user.getId());
            if (appCars != null) {
                for (AppCar appCar : appCars) {
                    AppGetCarsItem item = new AppGetCarsItem();
                    item.setPlate(appCar.getPlate());
                    //item.setAuth(appCar.getAuth());
                    AppUserCar appUserCar = appUserCarMapper.getByUserIdAndCarId(user.getId(), appCar.getId());
                    if (appUserCar != null) {
                        item.setAuth(appUserCar.getAuth() == AppUserCar.AUTH ? 1 : 0);
                    }
                    Parking parking = inParkingMapper.getParkingByPlate(appCar.getPlate());
                    if (parking == null) {
                        item.setLocation("该车辆目前没有进入任何停车场");
                    } else {
                        item.setLocation("该车辆目前停靠在" + ParkingUtil.getParkingName(parking.getName()));
                    }
                    plates.add(item);
                }
            }
            rsp.setResult(AppBusinessRsp.SUCCESS);
            rsp.setPlates(plates);
        }catch (Exception e) {
            logger.error("app用户获取自己的车辆异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public AppGetInParkingRsp getInParking(AppGetInParkingReq req) {
        AppGetInParkingRsp rsp = new AppGetInParkingRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            List<AppCar> appCars = appUserCarMapper.getCarByUserId(user.getId());
            if (appCars == null) {
                rsp.setResult(AppBusinessRsp.SUCCESS);
                rsp.setStrError("用户未注册车辆！");
                return rsp;
            }
            List<AppGetInParkingItem> list = new ArrayList<>();
            Date curDate = new Date();
            int endTime = (int) (DateUtil.getDateAfterSeconds(curDate, 60 * 60).getTime() / 1000);
            for (AppCar appCar : appCars) {
                InParking inParking = inParkingMapper.getByPlate(appCar.getPlate());
                if (inParking != null) {
                    AppGetInParkingItem item = new AppGetInParkingItem();
                    item.setPlate(inParking.getPlate());
                    item.setInTime(DateUtil.formatDate(inParking.getPrimaryInTime(), "yyyy-MM-dd HH:mm:ss"));
                    Parking parking = parkingMapper.getParkingById(inParking.getParkingId());
                    item.setParkingId(parking.getId());
                    item.setParkingName(ParkingUtil.getParkingName(parking.getName()));
                    item.setLockStatus(inParking.getLockStatus() == null ? 0 : inParking.getLockStatus());
                    int stayTime = (int) ((curDate.getTime() - inParking.getPrimaryInTime().getTime()) / 1000);
                    item.setStayTime(DateUtil.formatTime((long) stayTime));
                    try {
                        MqGetFeeRsp mqGetFeeRsp = mqService.getFee(inParking.getPlate(), inParking.getParkingId(), new Date());
                        DecimalFormat decimalFormat = new DecimalFormat("0.00");
                        item.setFee(decimalFormat.format(mqGetFeeRsp.getFee() * 0.01) + "元");
                        if (mqGetFeeRsp.getEndTime() < endTime) {
                            endTime = mqGetFeeRsp.getEndTime();
                        }
                        if (!"".equals(mqGetFeeRsp.getWarmPrompt())) {
                            item.setWarmPrompt("温馨提示：" + mqGetFeeRsp.getWarmPrompt());
                        }
                    } catch (CustomException e) {
                        item.setFee("未知");
                    }
                    list.add(item);
                }
            }
            rsp.setEndTime(endTime);
            rsp.setResult(AppBusinessRsp.SUCCESS);
            rsp.setRecords(list);
            rsp.setCount(list.size());
        } catch (Exception e) {
            logger.error("app用户获取场内信息异常：{}", e);
            rsp.setStrError("获取费用失败！");
        }
        return rsp;
    }

    @Override
    public AppGetFeeRsp getFee(AppGetFeeReq req) {
        AppGetFeeRsp rsp = new AppGetFeeRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }

        try {
            InParking inParking = inParkingMapper.getByPlate(req.getPlate());
            Parking parking = inParking == null ? null : parkingMapper.getParkingById(inParking.getParkingId());
            //Parking parking = inParkingMapper.getParkingByPlate(req.getPlate());
            if (parking == null) {
                rsp.setStrError("该车辆没有入场,获取停车费失败！");
                logger.info("app用户车辆({})获取停车费失败 ：该车辆没有入场!", req.getPlate());
                return rsp;
            }

            commonService.checkSupportOnlinePay(inParking);

            Date outTime = new Date();
            MqGetFeeRsp mqGetFeeRsp = mqService.getFee(req.getPlate(), parking.getId(), outTime);

            int stayTime = (int) ((outTime.getTime() - inParking.getPrimaryInTime().getTime()) / 1000);
            DecimalFormat decimalFormat = new DecimalFormat("0.00");
            rsp.setFee(decimalFormat.format(mqGetFeeRsp.getFee() * 0.01));
            rsp.setPlate(req.getPlate());
            rsp.setParkingName(ParkingUtil.getParkingName(parking.getName()));
            rsp.setInTime(DateUtil.formatDate(inParking.getPrimaryInTime(), "yyyy-MM-dd HH:mm"));
            rsp.setOutTime(DateUtil.formatDate(outTime, "yyyy-MM-dd HH:mm"));
            rsp.setStayTime(DateUtil.formatTime((long) stayTime));
            rsp.setEndTime(mqGetFeeRsp.getEndTime());
            rsp.setResult(AppBusinessRsp.SUCCESS);

            if (mqGetFeeRsp.getFee() != 0) {
                Date curTime = new Date();
                String orderNo = PayUtil.getOrderNo(parking.getId(), curTime);

                PayOrder payOrder = new PayOrder();
                payOrder.setUserToken(user.getToken());
                payOrder.setFee(mqGetFeeRsp.getFee());
                payOrder.setInfoId(mqGetFeeRsp.getInParkingId());
                payOrder.setInfoType(PayOrder.INFOTYPE_INPARKING);
                payOrder.setOrderNo(orderNo);
                payOrder.setTransactionId("0");
                payOrder.setFeeType(PayOrder.FEETYPE_SELF);
                payOrder.setPlate(req.getPlate());
                payOrder.setOutTime(outTime);
                payOrder.setCreatedTime(curTime);
                payOrder.setParkingId(parking.getId());
                payOrder.setTradeType(PayOrder.TRADETYPE_APP);
                payOrder.setPayWay(PayOrder.PAY_WAY_UNKNOWN);
                payOrder.setPayStatus(PayOrder.PAY_UNKNOWN);
                payOrderMapper.insertPayOrder(payOrder);
                rsp.setOrderNo(orderNo);
            }
        } catch (CustomException e) {
            rsp.setStrError(e.getMessage());
        } catch (Exception e) {
            logger.error("app用户获取停车费异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public AppGetInOutParkingRsp getInOutParking(AppGetInOutParkingReq req) {
        AppGetInOutParkingRsp rsp = new AppGetInOutParkingRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        rsp.setPageNum(req.getPageNum());
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            List<AppCar> appCars = appUserCarMapper.getCarByUserId(user.getId());
            if (appCars == null) {
                rsp.setResult(AppBusinessRsp.SUCCESS);
                rsp.setStrError("用户未注册车辆！");
                return rsp;
            }
            List<AppGetInOutParkingItem> list = new ArrayList<>();
            String[] plates = new String[3];
            for (int i = 0; i < appCars.size(); i++) {
                plates[i] = appCars.get(i).getPlate();
            }
            rsp.setCount(inOutParkingMapper.getCountByPlate(plates[0], plates[1], plates[2]));
            // limit条件查询
            int start = AppGetInOutParkingReq.PAGE_COUNT * req.getPageNum();
            int end = AppGetInOutParkingReq.PAGE_COUNT;
            List<InOutParking> inOutParkings = inOutParkingMapper.getByPlate(plates[0], plates[1], plates[2], start, end);
            if (inOutParkings == null) {
                rsp.setStrError("查询行车记录失败！");
                logger.info("app用户在inoutparking表中查询车辆行车记录失败，数据库返回null");
                return rsp;
            }

            if (inOutParkings.size() > 0) {
                for (InOutParking inOutParking : inOutParkings) {
                    AppGetInOutParkingItem item = new AppGetInOutParkingItem();
                    item.setPlate(inOutParking.getCarLicense());
                    item.setParkingName(ParkingUtil.getParkingName(inOutParking.getParkingName()));
                    if (inOutParking.getPrimaryInTime() != null) {
                        item.setInTime(DateUtil.formatDate(inOutParking.getPrimaryInTime(), "yyyy-MM-dd HH:mm:ss"));
                    }
                    if (inOutParking.getPrimaryOutTime() != null) {
                        item.setOutTime(DateUtil.formatDate(inOutParking.getPrimaryOutTime(), "yyyy-MM-dd HH:mm:ss"));
                        item.setWeek(DateUtil.getWeek(inOutParking.getPrimaryOutTime()));
                        item.setTime(inOutParking.getPrimaryOutTime().getTime());
                    }
                    List<FeeDetail> feeDetails;
                    if (inOutParking.getLocalInoutparkingId() != null && inOutParking.getLocalInoutparkingId() != 0) {  // 本地记录id存在
                        feeDetails = feeDetailMapper.getByInoutParkingId(inOutParking.getLocalInoutparkingId(), inOutParking.getParkingId());
                    } else {    // 车场旧数据，inoutparking中没有本地记录id
                        feeDetails = feeDetailMapper.getByCloudInoutParkingId(inOutParking.getId(), inOutParking.getParkingId());
                    }

                    if (feeDetails != null && feeDetails.size() > 0 && feeDetails.get(0) != null) {
                        DecimalFormat decimalFormat = new DecimalFormat("0.00");
                        FeeDetail feeDetail = feeDetails.get(0);
                        item.setFee(decimalFormat.format(feeDetail.getActualfee() * 0.01));
                        if (feeDetail.getCashPay() != null && feeDetail.getCashPay() == 0) {
                            item.setPayWay("网络支付");
                        } else {
                            item.setPayWay("线下支付");
                        }
                    }
                    if (inOutParking.getPrimaryStayTime() != null && inOutParking.getPrimaryStayTime() > 0) {
                        item.setStayTime(DateUtil.formatTime((long) inOutParking.getPrimaryStayTime()));
                    }
                    list.add(item);
                }
                rsp.setResult(AppBusinessRsp.SUCCESS);
                rsp.setRecords(list);
                logger.info("app用户查询行车记录成功，共{}条记录！", inOutParkings.size());
            } else {
                rsp.setResult(AppBusinessRsp.SUCCESS);
                logger.info("app用户未查询车辆行车记录({},{})", start, end);
            }

        } catch (Exception e) {
            logger.error("app用户获取行车记录异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public AppCarLockOrNoRsp carLockOrNo(AppCarLockOrNoReq req) {
        AppCarLockOrNoRsp rsp = new AppCarLockOrNoRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            checkParam.getAppCar(req.getToken(), req.getPlate());

            InParking inParking = inParkingMapper.getByPlate(req.getPlate());
            Parking parking = inParking == null ? null : parkingMapper.getParkingById(inParking.getParkingId());
            if (parking == null) {
                rsp.setStrError("该车辆未入场！");
                return rsp;
            }

            // 如果传了 车辆锁定状态，使用传的参数， 没传，锁定的则解锁
            int lockStatus = inParking.getLockStatus() == null ? 0 : inParking.getLockStatus();
            Integer reqLockStatus = req.getStatus();
            if (reqLockStatus != null) {
                if (reqLockStatus == lockStatus) {  // 重复锁定或解锁，直接返回成功
                    rsp.setResult(AppBusinessRsp.SUCCESS);
                    return rsp;
                }
            } else {
                reqLockStatus = lockStatus == 1 ? 0 : 1;
            }

            mqService.carLockOrNo(req.getPlate(), parking.getId(), reqLockStatus);
            inParkingMapper.updateLockStatus(reqLockStatus, inParking.getId());
            rsp.setResult(AppBusinessRsp.SUCCESS);
        } catch (CustomException e) {
            rsp.setStrError(e.getMessage());
        } catch (Exception e) {
            logger.error("app用户获取场内信息异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public AppFeedbackRsp feedback(AppFeedbackReq req) {
        AppFeedbackRsp rsp = new AppFeedbackRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            String content = req.getContent();
            if (content == null || content.trim().length() == 0) {
                rsp.setStrError("反馈意见不能为空！");
                return rsp;
            }
            AppFeedback feedback = new AppFeedback();
            feedback.setUserId(user.getId());
            feedback.setContent(content.trim());
            feedback.setCreatedTime(new Date());
            appFeedbackMapper.insertFeedback(feedback);
            rsp.setResult(AppBusinessRsp.SUCCESS);
        } catch (Exception e) {
            logger.error("处理app用户的反馈意见异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public AppGetInfoRsp getInfo(AppBusinessReq req) {
        AppGetInfoRsp rsp = new AppGetInfoRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            rsp.setEbBalance("0.00");
            rsp.setDiscount("0.00");
            rsp.setPic(new byte[1]);
            StringBuffer mobile = new StringBuffer(user.getMobile()).insert(3, "-").insert(8, "-");
            rsp.setMobile(mobile.toString());
            rsp.setResult(AppBusinessRsp.SUCCESS);
        } catch (Exception e) {
            logger.error("app用户获取个人信息异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public AppGetUserInfoRsp getUserInfo(AppBusinessReq req) {
        AppGetUserInfoRsp rsp = new AppGetUserInfoRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            rsp.setEbBalance("0.00");
            if (user.getPortraitPath() == null || "".equals(user.getPortraitPath())) {
                rsp.setImageUrl(basicProperties.getAppUserDefaultPortrait());
            } else {
                String serverAddress;
                if (basicProperties.getServerAddress() == null || basicProperties.getServerAddress().equals("")) {
                    serverAddress = "http://open.cheyifu2016.com:" + basicProperties.getHttpPort();
                } else {
                    serverAddress = "http://" + basicProperties.getServerAddress() + ":" + basicProperties.getHttpPort();
                }
                String portraitPath = user.getPortraitPath();
                String fileName = portraitPath.substring(portraitPath.lastIndexOf("/")+1, portraitPath.lastIndexOf("."));
                rsp.setImageUrl(serverAddress + "/app/getPortrait/" + user.getId() + "?fileName=" + fileName);
            }
            List<MerchantCoupon> merchantCoupons = merchantCouponMapper.getByAppUserIdAndStatus(user.getId(), MerchantCoupon.UNUSED);
            if (merchantCoupons == null || merchantCoupons.size() == 0) {
                rsp.setCouponCount(0);
            } else {
                int couponCount = 0;
                for (MerchantCoupon merchantCoupon : merchantCoupons) {
                    Integer parkingId = merchantCoupon.getParkingId();
//                    Parking parking = parkingMapper.getParkingById(parkingId);
                    LocalAdminpara localAdminpara = localAdminparaMapper.getByParkingIdAndParaKey(parkingId, LocalAdminpara.USE_COUPON);
                    if (localAdminpara == null || StringUtils.isEmpty(localAdminpara.getParaValue())
                            || Integer.parseInt(localAdminpara.getParaValue()) != Parking.ENABLE_COUPON) {
                        continue;
                    }
                    if (merchantCoupon.getCouponType() == MerchantCoupon.COUPON_TYPE_CHANGE_FEEGROUP) {
                        continue;
                    }
                    couponCount++;
                }
                rsp.setCouponCount(couponCount);
            }
            StringBuffer mobile = new StringBuffer(user.getMobile()).insert(3, "-").insert(8, "-");
            rsp.setMobile(mobile.toString());
            rsp.setResult(AppBusinessRsp.SUCCESS);
        } catch (Exception e) {
            logger.error("app用户获取个人信息异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public IllegalQuery illegalQuery(AppIllegalQueryReq req) {
        IllegalQuery rsp = new IllegalQuery();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            String carcode = req.getCarcode();
            String cardrive = req.getCardrive();
            List<AppCar> appCars = appUserCarMapper.getCarByUserId(user.getId());
            if (appCars != null) {
                boolean isUserCar = false; // 是否是用户注册车辆
                AppCar appCar = null;
                for (AppCar appCar1 : appCars) {
                    if (appCar1.getPlate().equals(req.getPlate().trim().toUpperCase())) {
                        isUserCar = true;
                        appCar = appCar1;
                    }
                }
                if (isUserCar) {
                    AppUserCar appUserCar = appUserCarMapper.getByUserIdAndCarId(user.getId(), appCar.getId());
                    if (appUserCar.getAuth() == AppUserCar.AUTH) {
                        carcode = appCar.getCarcode();
                        cardrive = appCar.getCardrive();
                    }
                }
            }

            String url = illegalQueryUtil.getUrl(user.getMobile(), req.getPlate(), carcode, cardrive, user.getToken());
            logger.info("违章查询url：{}", url);
            rsp.setUrl(url);
            rsp.setResult(AppBusinessRsp.SUCCESS);
        } catch (Exception e) {
            logger.error("app用户违章查询异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public AppCarAuthRsp carAuth(AppCarAuthReq req) {
        AppCarAuthRsp rsp = new AppCarAuthRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            AppCar appCar = checkParam.getAppCar(user, req.getPlate());appUserCarMapper.getCarByUserId(user.getId());
            Map<String, String> map = illegalQueryUtil.auth(user.getMobile(), req.getPlate(), req.getCarcode(), req.getCardrive(), user.getToken() + new Date().getTime());

            AppUserCar appUserCar = appUserCarMapper.getByUserIdAndCarId(user.getId(), appCar.getId());
            appUserCar.setCarcode(req.getCarcode());
            appUserCar.setCardrive(req.getCardrive());
            if ("fail".equals(map.get("auth"))) {
                logger.info("用户认证失败：{}", map.get("errMsg"));
                rsp.setStrError("用户认证失败！");
                appUserCar.setAuth(AppUserCar.UNAUTH);
                appUserCarMapper.updateAuthInfo(appUserCar);
            } else {
                appUserCar.setAuth(AppUserCar.AUTH);
                appUserCarMapper.updateAuthInfo(appUserCar);

                appCar.setCarcode(req.getCarcode());
                appCar.setCardrive(req.getCardrive());
                appCarMapper.updateAuthInfo(appCar);
                rsp.setResult(AppBusinessRsp.SUCCESS);
            }
        } catch (CustomException e) {
            rsp.setStrError(e.getMessage());
        } catch (Exception e) {
            logger.error("app用户车辆认证异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public AppGetImageUrlsRsp getUrls() {
        AppGetImageUrlsRsp rsp = new AppGetImageUrlsRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        try {
            rsp.setUrls(basicProperties.getAppImageUrls());
            rsp.setResult(AppBusinessRsp.SUCCESS);
        } catch (Exception e) {
            logger.error("获取启动页和首页轮播图url异常:{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public AppCheckForUpdateRsp checkForUpdate(AppCheckForUpdateReq req) {
        AppCheckForUpdateRsp rsp = new AppCheckForUpdateRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        BufferedReader reader = null;
        try {
            String versionStr = req.getVersion();
            if (StringUtils.isEmpty(versionStr)) {
                rsp.setStrError("版本号错误，检查更新失败！");
                return rsp;
            }
            int version = Integer.parseInt(versionStr.replace(".", ""));
            String filePath;
            if (req.getAppId() == null || req.getAppId() == 1) {    // 易停宝
                User user = checkParam.getAppUser(req.getToken());
                if (!versionStr.equals(user.getVersion())) {
                    user.setVersion(versionStr);
                    userMapper.updateVersion(user);
                }
                filePath = basicProperties.getAppVersionFilePath();
            } else if (req.getAppId() == 2){    // 商户发布优惠券app
                filePath = basicProperties.getAppVersionFilePathForMerchant();
            } else if (req.getAppId() == 4){
                filePath = basicProperties.getSvrAppVersionFile();
            }else{
                HandsetLogin handsetLogin = handsetLoginMapper.getByToken(req.getToken());
                NpsManageAccount npsManageAccount = handsetLogin == null ? null :npsManageAccountMapper.getById(handsetLogin.getNpsMAccountId());
                if (npsManageAccount == null) {
                    rsp.setStrError("登录超时，请重新登录");
                    return rsp;
                }
                if (!versionStr.equals(npsManageAccount.getVersion())) {
                    npsManageAccount.setVersion(versionStr);
                    npsManageAccountMapper.updateVersion(npsManageAccount);
                }
                filePath = basicProperties.getAppVersionFilePathForHandset();
            }

            // 读取版本文件
            File file = new File(filePath);
            if (!file.exists()) {
                rsp.setStrError("服务器异常！");
                return rsp;
            }
            reader = new BufferedReader(new FileReader(file));
            String tempStr;
            boolean flag = false;   // 传的版本号是否存在
            int newVersion = version;   // 最新的版本号
            while ((tempStr = reader.readLine()) != null) { // 一次读入一行，直到读入null为文件结束
                if (!"".equals(tempStr.trim())) {
                    int tempVersion = Integer.parseInt(tempStr.trim().replace(".", ""));
                    if (tempVersion == version) {
                        flag = true;
                        continue;
                    }
                    if (flag) {
                        newVersion = tempVersion;
                    }
                }
            }
            rsp.setResult(AppBusinessRsp.SUCCESS);
            rsp.setCheckForUpdate((flag && newVersion != version) ? AppCheckForUpdateRsp.UPDATE : AppCheckForUpdateRsp.UNUPDATE);
        }  catch (CustomException e) {
            rsp.setStrError(e.getMessage());
        } catch (IOException e) {
            logger.error("app检查是否需要更新异常：{}", e);
            rsp.setStrError("服务器异常！");
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("app检查是否需要更新，关闭流异常：{}", e);
                }
            }
        }
        return rsp;
    }

    @Override
    public AppUploadAuthPicRsp uploadAuthPic(AppUploadAuthPicReq req) {
        AppUploadAuthPicRsp rsp = new AppUploadAuthPicRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            MultipartFile file = req.getFile();
            if (file.isEmpty()) {
                rsp.setStrError("文件不能为空！");
                return rsp;
            }
            String plate = req.getPlate().trim().toUpperCase();
            AppCar appCar = appCarMapper.getByPlate(plate);
            if (appCar == null) {
                rsp.setStrError("用户未注册此车辆！");
                return rsp;
            }
            AppUserCar appUserCar = appUserCarMapper.getByUserIdAndCarId(user.getId(), appCar.getId());
            if (appUserCar == null) {
                rsp.setStrError("用户未注册此车辆！");
                return rsp;
            }
            // 保存文件
            String dirPath = basicProperties.getAppAuthFilePath();
            String fileName = user.getId() + "_" + appCar.getId();
            FileUtil.saveFile(file, dirPath, fileName);
            // 更新数据库
//            appUserCar.setFilepath(dirPath + fileName + ".jpg");
            appUserCarMapper.updateFilePath(dirPath + fileName + ".jpg", appUserCar.getId());
            rsp.setResult(AppBusinessRsp.SUCCESS);
        } catch (Exception e) {
            logger.error("app用户上传车辆认证图片异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public AppIllegalQueryFormRsp getIllegalQueryForm(AppIllegalQueryFormReq req) {
        AppIllegalQueryFormRsp rsp = new AppIllegalQueryFormRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            if (req.getPlate().length() < 7) {
                rsp.setStrError("车牌号不正确！");
                return rsp;
            }
            String illegalQueryRuleOfCity = IllegalQueryUtil.getIllegalQueryRuleOfCity(req.getPlate().substring(0, 2).toUpperCase());
            if (illegalQueryRuleOfCity == null || illegalQueryRuleOfCity.length() != 2) {
                rsp.setStrError("该城市暂不支持查询！");
            } else {
                rsp.setResult(AppBusinessRsp.SUCCESS);
                rsp.setShowCarcode("1".equals(illegalQueryRuleOfCity.substring(0, 1)) ? AppIllegalQueryFormRsp.SHOW : AppIllegalQueryFormRsp.HIDE);
                rsp.setShowCardrive("1".equals(illegalQueryRuleOfCity.substring(1)) ? AppIllegalQueryFormRsp.SHOW : AppIllegalQueryFormRsp.HIDE);
            }
        } catch (Exception e) {
            logger.error("app获取违章查询页面数据异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public AppGetCouponRsp getCoupon(AppGetCouponReq req) {
        AppGetCouponRsp rsp = new AppGetCouponRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {

            List<MerchantCoupon> merchantCoupons = null;
//            优惠券状态 1停车场券 2车易付券 3商家券 0失效
            switch (req.getCouponStatus()) {
                case 1: // 停车场券
                    merchantCoupons = merchantCouponMapper.getParkingCouponByAppUserIdAndStatus(user.getId(), MerchantCoupon.UNUSED);
                    break;
                case 2: // 车易付券
                    merchantCoupons = merchantCouponMapper.getCyfCouponByAppUserIdAndStatus(user.getId(), MerchantCoupon.UNUSED);
                    break;
                case 3: // 商家券
                    break;
                case 0:
                    merchantCoupons = merchantCouponMapper.getUnUsedByAppUserId(user.getId());
                    break;
                default: {

                }
            }

            if (merchantCoupons != null && merchantCoupons.size() > 0) {
                ArrayList<AppGetCouponItem> coupons = new ArrayList<>();
                DateFormat dateFormat = AppGetCouponItem.DATE_FORMAT;
                DecimalFormat decimalFormat = new DecimalFormat("0.00");
                for (MerchantCoupon merchantCoupon : merchantCoupons) {
                    Integer parkingId = merchantCoupon.getParkingId();
                    Parking parking = parkingMapper.getParkingById(parkingId);
                    LocalAdminpara localAdminpara = localAdminparaMapper.getByParkingIdAndParaKey(parkingId, LocalAdminpara.USE_COUPON);
                    if (parking == null || localAdminpara == null || StringUtils.isEmpty(localAdminpara.getParaValue())
                            || Integer.parseInt(localAdminpara.getParaValue()) != Parking.ENABLE_COUPON) {
                        continue;
                    }
                    AppGetCouponItem item = new AppGetCouponItem();
                    item.setStartTime(dateFormat.format(merchantCoupon.getCreatedTime()));
                    item.setEndTime(dateFormat.format(merchantCoupon.getEndTime()));
                    item.setType(merchantCoupon.getCouponType());
                    if (merchantCoupon.getCouponType() == MerchantCoupon.COUPON_TYPE_HOURS) {
                        item.setFree(merchantCoupon.getFreeHours() / 60 + "Min");
                    } else if (merchantCoupon.getCouponType() == MerchantCoupon.COUPON_TYPE_AMOUNT){
                        if (merchantCoupon.getFreeAmount() % 100 == 0) {
                            item.setFree("￥" + merchantCoupon.getFreeAmount() / 100);
                        } else {
                            item.setFree("￥" + decimalFormat.format(merchantCoupon.getFreeAmount() * 0.01));
                        }
                    } else {
                        continue;
                    }
                    item.setCouponCode(merchantCoupon.getCouponCode());
                    if (parking.getId() == 1) {
                        item.setPublisher("车易付官方");
                    } else {
                        item.setPublisher(ParkingUtil.getParkingName(parking.getName()));
                    }
                    item.setCouponCode(merchantCoupon.getCouponCode());
                    coupons.add(item);
                }
                rsp.setCoupons(coupons);
            }
            rsp.setResult(AppBusinessRsp.SUCCESS);
        } catch (Exception e) {
            rsp.setStrError("服务器异常");
            logger.error("app用户获取优惠券异常：{}", e);
        }
        return rsp;
    }

    @Override
    @Transactional
    public AppPostPortraitRsp postPortrait(AppPostPortraitReq req) {
        AppPostPortraitRsp rsp = new AppPostPortraitRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            MultipartFile file = req.getFile();
            if (file.isEmpty()) {
                rsp.setStrError("文件不能为空！");
                return rsp;
            }
            String oldPortraitPath = user.getPortraitPath();
            // 保存文件
            String pathname = basicProperties.getAppPortraitFilePath() + (user.getId() / 1000 + 1) + "/";
            String fileName = user.getId() + "_" + DateUtil.formatDate(new Date(), "HHmmss");
            FileUtil.saveFile(file, pathname, fileName);

            // 更新数据库
            userMapper.updatePortraitPath(pathname + fileName + ".jpg", user.getId());
            rsp.setResult(AppBusinessRsp.SUCCESS);

            if (oldPortraitPath != null && !"".equals(oldPortraitPath)) {
                File oldPortraitFile = new File(oldPortraitPath);
                if (oldPortraitFile.exists()) {
                    boolean delete = oldPortraitFile.delete();
                    if (!delete) {
                        logger.error("删除旧头像失败！({})", oldPortraitPath);
                    } else {
                        logger.info("删除旧头像成功！({})", oldPortraitPath);
                    }
                } else {
                    logger.info("旧头像未找到，不删除！({})", oldPortraitPath);
                }
            }
        } catch (CustomException e) {
            rsp.setStrError(e.getMessage());
        } catch (Exception e) {
            logger.error("app用户头像上传异常：{}", e);
            rsp.setStrError("上传失败！");
        }
        return rsp;
    }

    @Override
    public AppUploadVersionForIosRsp uploadVersionForIos(AppUploadVersionForIosReq req) {
        AppUploadVersionForIosRsp rsp = new AppUploadVersionForIosRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            userMapper.updateIosVersion(req.getVersion(), user.getId());
            rsp.setResult(AppBusinessRsp.SUCCESS);
        } catch (Exception e) {
            logger.error("app用户上传ios版本异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    @Transactional
    public AppEditCarRsp editCar(AppEditCarReq req) {
        AppEditCarRsp rsp = new AppEditCarRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            AppCar oldAppCar = checkParam.getAppCar(user, req.getOldPlate());
            if (req.getOldPlate().equals(req.getPlate())) {
                oldAppCar.setType(req.getType());
                oldAppCar.setColor(req.getColor());
                oldAppCar.setBrand(req.getBrand());
                oldAppCar.setIsEnergy(req.getIsEnergy());
                oldAppCar.setCheckTime(req.getCheckTime());
                oldAppCar.setRegisterTime(req.getRegisterTime());
                oldAppCar.setMileage(req.getMileage());
                appCarMapper.updateAppCar(oldAppCar);
                rsp.setResult(AppBusinessRsp.SUCCESS);
                return rsp;
            }
            List<AppCar> appCars = checkParam.getAppCars(user);
            for (AppCar appCar : appCars) {
                if (appCar.getPlate().equals(req.getPlate())) {
                    rsp.setStrError("您已绑定该车辆！");
                    return rsp;
                }
            }
            AppCar appCar = appCarMapper.getByPlate(req.getPlate());
            if (appCar == null) {
                appCar = new AppCar();
                appCar.setPlate(req.getPlate());
                appCar.setType(req.getType());
                appCar.setColor(req.getColor());
                appCar.setBrand(req.getBrand());
                appCar.setIsEnergy(req.getIsEnergy());
                appCar.setCheckTime(req.getCheckTime());
                appCar.setRegisterTime(req.getRegisterTime());
                appCar.setMileage(req.getMileage());
                appCarMapper.insertAppCar(appCar);
            } else {
                appCar.setPlate(req.getPlate());
                appCar.setType(req.getType());
                appCar.setColor(req.getColor());
                appCar.setBrand(req.getBrand());
                appCar.setIsEnergy(req.getIsEnergy());
                appCar.setCheckTime(req.getCheckTime());
                appCar.setRegisterTime(req.getRegisterTime());
                appCar.setMileage(req.getMileage());
                appCarMapper.updateAppCar(appCar);
            }
            appUserCarMapper.deleteByUserIdAndCarId(user.getId(), oldAppCar.getId());
            appUserCarMapper.insertUserCar(user.getId(), appCar.getId());
            rsp.setResult(AppBusinessRsp.SUCCESS);
        } catch (CustomException e) {
            rsp.setStrError(e.getMessage());
        } catch (Exception e) {
            logger.error("app用户修改车辆信息异常：{}", e);
            rsp.setStrError("服务器异常");
            // 手动回滚，controller层无需处理异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return rsp;
    }

    @Override
    public AppDeleteCarRsp deleteCar(AppDeleteCarReq req) {
        AppDeleteCarRsp rsp = new AppDeleteCarRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            AppCar appCar = checkParam.getAppCar(user, req.getPlate());
            appUserCarMapper.deleteByUserIdAndCarId(user.getId(), appCar.getId());
            rsp.setResult(AppBusinessRsp.SUCCESS);
        } catch (CustomException e) {
            rsp.setStrError(e.getMessage());
        } catch (Exception e) {
            logger.error("app用户删除车辆异常：{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    @Override
    public File getPortrait(AppGetPortraitReq req) {
        try {
            User user = userMapper.getById(req.getAppUserId());
            if (user != null) {
                String filePath = user.getPortraitPath();
                File file = new File(filePath);
                if (!file.exists()) {
                    logger.info("头像({})不存在！", filePath);
                    return null;
                } else {
                    return file;
                }
            }
        } catch (Exception e) {
            logger.error("获取文件异常：{}", e);
        }
        return null;
    }

    @Override
    public AppGetAdRsp getAd(AppGetAdReq req) {
        AppGetAdRsp rsp = new AppGetAdRsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        User user;
        try {
            user = checkParam.getAppUser(req.getToken());
        } catch (CustomException e) {
            rsp.setResult(AppBusinessRsp.TIMEOUT);
            rsp.setStrError(e.getMessage());
            return rsp;
        }
        try {
            List<AppGetAdItem> ads = new ArrayList<>();
            WeChatSubscriptionUtil.GetLastNewsRsp news = weChatSubscriptionUtil.getLastNews();
            AppGetAdItem item = new AppGetAdItem();
            item.setAuthor(news.getAuthor());
            item.setTime(DateUtil.formatDate(DateUtil.convertSeconds2Date(news.getTime()), "yyyy-MM-dd"));
            item.setPortraitUrl(news.getPortraitUrl());
            item.setPicUrl(news.getPicUrl());
            item.setUrl(news.getUrl());
            ads.add(item);
            rsp.setAds(ads);
            rsp.setResult(AppBusinessRsp.SUCCESS);
        } catch (CustomException e) {
            rsp.setStrError(e.getMessage());
        } catch (Exception e) {
            logger.error("获取首页下方广告异常：{}", e);
            rsp.setStrError("服务器异常！");
        }
        return rsp;
    }

    @Override
    public AppGetImgUrlsAndMd5Rsp getUrlsAndMd5(AppGetImgUrlsAndMd5Req req) {
        AppGetImgUrlsAndMd5Rsp rsp = new AppGetImgUrlsAndMd5Rsp();
        rsp.setResult(AppBusinessRsp.FAIL);
        try {
            rsp.setUrlList(getImgUrlsAndMd5s(req.getUrlType()));
            rsp.setResult(AppBusinessRsp.SUCCESS);
        } catch (CustomException e) {
            rsp.setStrError(e.getMessage());
        } catch (Exception e){
            logger.error("获取图片链接和md5异常:{}", e);
            rsp.setStrError("服务器异常");
        }
        return rsp;
    }

    private ArrayList<AppGetImageUrlsItem> getImgUrlsAndMd5s(int urlType) throws CustomException {
        ArrayList<AppGetImageUrlsItem> urlList = new ArrayList<>();
        Adminpara adminpara;
        switch (urlType) {
            case AppGetImgUrlsAndMd5Req.URLTYPE_STARTPAGE:
                adminpara = adminparaMapper.getByParaKey(Adminpara.APP_STARTPAGE_IMGURLS);
                break;
            case AppGetImgUrlsAndMd5Req.URLTYPE_HOMEPAGE:
                adminpara = adminparaMapper.getByParaKey(Adminpara.APP_HOMEPAGE_IMGURLS);
                break;
            default:{
                throw new CustomException("参数错误！");
            }
        }
        if (adminpara != null && adminpara.getParaValue() != null && !"".equals(adminpara.getParaValue().trim())
                && adminpara.getMemo() != null && !"".equals(adminpara.getMemo().trim())) {
            String[] startPageImgUrls = adminpara.getParaValue().trim().split(",");
            String[] startPageImgMd5s = adminpara.getMemo().trim().split(",");
            for (int i = 0; i < startPageImgUrls.length; i++) {
                AppGetImageUrlsItem item = new AppGetImageUrlsItem();
                item.setUrl(startPageImgUrls[i]);
                item.setMd5(startPageImgMd5s[i]);
                urlList.add(item);
            }
        }
        return urlList;
    }
}
